package com.common.web.aop;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.common.api.annontation.Authority;
import com.common.api.exception.CommonException;
import com.common.web.service.JwtTokenUtil;
import com.common.web.util.RequestUtil;
import com.common.web.util.WebConstant;

/**
 * 服务日志切面
 * @author	ficus
 */
@Aspect
@Component
@Order(2)
public class AuthorityAspect{

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
	
	/**
	 * 设置切入点，方法上标记了ApiOperation注解的将会被切入.
	 */
	@Pointcut("@annotation(com.common.api.annontation.Authority)")
	public void pointcut() {
	}

	/**
	 * 根据切入点做环绕通知.
	 * @param point
	 * @return
	 */
	@Before("pointcut()")
	public void before(JoinPoint point) throws Throwable {
		HttpServletRequest request = RequestUtil.getRequest();
		String token = request.getHeader(WebConstant.TOKEN_KEY);
		List<String> authorityList = jwtTokenUtil.getAuthorityList(token);
		if(CollectionUtils.isEmpty(authorityList)) {
			throw new CommonException("当前用户没有访问该接口的权限,请设置权限再调用");
		}
		// 验证权限
		MethodSignature signature = (MethodSignature) point.getSignature();
		Authority authority = signature.getMethod().getAnnotation(Authority.class);
		String[] authous = authority.authous();
		for (String string : authous) {
			if(authorityList.contains(string)) {
				return ;
			}
		}
		throw new CommonException("当前用户没有访问该接口的权限,请设置权限再调用");
	}
}
